<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    /* canvas{
      background-color: skyblue
    } */
  </style>
</head>
<body>
  <canvas id="canvas"></canvas>
  <script>
    /** @type {HTMLCanvasElement} */
     var canvas=document.querySelector("#canvas")
    var ctx=canvas.getContext("2d")
    canvas.width=800
    canvas.height=800
    function Ball(x,y,vx,vy,color){
      this.x=x
      this.y=y
      this.vx=vx
      this.vy=vy
      this.color=color
      this.draw=function(){
        ctx.beginPath()
        ctx.save()
        ctx.fillStyle=this.color
        ctx.arc(this.x,this.y,1,0,Math.PI*2)
        ctx.fill()
        ctx.restore()
        ctx.closePath()
        this.update()
      }
      this.update=function(){
        this.x+=this.vx
        this.y+=this.vy
        // console.log(1);
      }
    }
    //图片性能太差！！！
    var balls=[]
    var img=new Image()
    img.crossOrigin = 'Annoymous'
    img.src="https://c-ssl.duitang.com/uploads/item/201907/22/20190722171500_fshfb.thumb.1000_0.jpg"
    //canvas.width和img.width大小不一样！用canvas.width,因为图片目前呈现在画布上，画布最保险！
    img.onload=function(){
      ctx.drawImage(img,0,0,canvas.width,canvas.height)
      var data=ctx.getImageData(0,0,canvas.width,canvas.height).data
      // console.log(data);
      ctx.clearRect(0,0,canvas.width,canvas.height)
      for(var i=0;i<data.length;i+=16){//隔几个像素点取一个像素点
        let x=i/4%canvas.width
        // console.log(x);
        let y=i/4/canvas.width|0+2
        let r=data[i]
        let g=data[i+1]
        let b=data[i+2]
        let a=data[i+3]
        let vx=(Math.random()-0.5)*10
        let vy=(Math.random()-0.5)*10
        let rgba="rgba("+r+","+g+","+b+","+a+")"
        let ball=new Ball(x,y,vx,vy,rgba)
        // ball.draw()
        balls.push(ball)
      }
      // ctx.clearRect(0,0,canvas.width,canvas.height)
      // drawData()
    }
    // var ball=[]
    function drawData(){
      ctx.clearRect(0,0,canvas.width,canvas.height)
      for(var j=0;j<balls.length;j++){
        balls[j].draw()
        // 
        // console.log("11");
      }
      requestAnimationFrame(drawData)
      console.log("11");
    }
    drawData()
  </script>
</body>
</html>